import 'dart:math';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';

class ScreenUtil {
  static const Size defaultSize = Size(360, 690);

  ScreenUtil._();

  factory ScreenUtil() {
    return _instance;
  }

  static late ScreenUtil _instance;

  /// UI设计中手机尺寸 , dp
  late Size uiSize;

  ///屏幕方向
  late Orientation _orientation;

  late double _screenWidth;
  late double _screenHeight;
  late double _statusBarHeight;
  late double _bottomBarHeight;
  late double _pixelRatio;
  late double _textScaleFactor;

  ///获取屏幕方向
  Orientation get orientation => _orientation;

  /// 当前设备宽度 dp
  double get screenWidth => _screenWidth;

  ///当前设备高度 dp
  double get screenHeight => _screenHeight;

  /// 状态栏高度 dp 刘海屏会更高
  double get statusBarHeight => _statusBarHeight / _pixelRatio;

  /// 底部安全区距离 dp
  double get bottomBarHeight => _bottomBarHeight / _pixelRatio;

  /// 设备的像素密度
  double get pixelRatio => _pixelRatio;

  /// 每个逻辑像素的字体像素数，字体的缩放比例
  double get textScaleFactor => _textScaleFactor;

  /// 宽度缩放，实际尺寸与UI设计的比例
  double get scaleWidth => _screenWidth / uiSize.width;

  /// 高度缩放
  double get scaleHeight => _screenHeight / uiSize.height;

  double get scaleText => min(scaleWidth, scaleHeight);

  /// 根据UI设计的设备宽度适配
  /// 高度也可以根据这个来做适配可以保证不变形,比如你想要一个正方形的时候.
  double setWidth(num width) => width * scaleWidth;

  /// 根据UI设计的设备高度适配
  /// 当发现UI设计中的一屏显示的与当前样式效果不符合时,
  /// 或者形状有差异时,建议使用此方法实现高度适配.
  /// 高度适配主要针对想根据UI设计的一屏展示一样的效果
  double setHeight(num height) => height * scaleHeight;

  ///根据宽度或高度中的较小值进行适配
  double radius(num r) => r * scaleText;

  ///字体大小适配方法
  double setSp(num fontSize) => fontSize * scaleText;

  static void init(
    BoxConstraints constraints, {
    Orientation orientation = Orientation.portrait,
    Size designSize = defaultSize,
  }) {
    _instance = ScreenUtil._()
      ..uiSize = designSize
      .._orientation = orientation
      .._screenWidth = constraints.maxWidth
      .._screenHeight = constraints.maxHeight;

    var window = WidgetsBinding.instance?.window ?? ui.window;
    _instance._statusBarHeight = window.padding.top;
    _instance._bottomBarHeight = window.padding.bottom;
    _instance._pixelRatio = window.devicePixelRatio;
    _instance._textScaleFactor = window.textScaleFactor;
  }
}
